//
//  JsonCR2.m
//  Interventix
//
//  Created by Diego on 05/12/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "JsonCR2.h"
#import "SBJson.h"
#import "CryptoCR2.h"
#import "NSData+Conversion.h"
#include <stdlib.h>

@implementation JsonCR2

bool const DEBUG_RESPONSE = false;
bool const DEBUG_REQUEST = false;
bool const DEBUG_READ = false;


+(NSDictionary *) read:(NSString *) stringCR2{
    if(DEBUG_READ){
        //NSLog(@"READ:%@",stringCR2);
        return [stringCR2 JSONValue];
    }else{
        NSString *dec = [CryptoCR2 decrypt:stringCR2];
        //NSLog(@"DEC: %@",dec);
        return [dec JSONValue];
    }
}


+(NSString *) createRequest:(NSString *)section action:(NSString *) action paramters:(NSDictionary *) params iduser:(NSNumber *) iduser{
    NSMutableDictionary *json = [[NSMutableDictionary alloc]initWithCapacity:0];
    
    NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
    long long t = [[NSNumber numberWithDouble: timeStamp] doubleValue] * 1000;
    NSNumber *num = [NSNumber numberWithLongLong:t];
    NSString *obf = [NSString stringWithFormat:@"%x%llx%x",arc4random_uniform(999999),t,arc4random_uniform(999999)];
    [json setObject:obf forKey:@"obfuscator"];
    [json setObject:num forKey:@"datetime"];
    
    
    [json setObject:action forKey:@"action"];
    [json setObject:section forKey:@"section"];
    
    [json setObject:iduser forKey:@"iduser"];

    [json setObject:params  forKey:@"parameters"];
        
    if (DEBUG_REQUEST) {
        return [json JSONRepresentation];
    } else {
        return [CryptoCR2 encrypt:[json JSONRepresentation]];
    }
}

+(NSString *) createRequestLogin:(NSString *)username andPassword:(NSString *) password{
    
    NSMutableDictionary *json = [[NSMutableDictionary alloc]initWithCapacity:0];
    
    NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
    long long t = [[NSNumber numberWithDouble: timeStamp] doubleValue] * 1000;
    NSNumber *num = [NSNumber numberWithLongLong:t];
    NSString *obf = [NSString stringWithFormat:@"%x%llx%x",arc4random_uniform(999999),t,arc4random_uniform(999999)];
    [json setObject:obf forKey:@"obfuscator"];
    [json setObject:num forKey:@"datetime"];
    
    
    [json setObject:@"login" forKey:@"action"];
    [json setObject:@"users" forKey:@"section"];
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithCapacity:0];
    
    [params setObject:password forKey:@"password"];
    [params setObject:username forKey:@"username"];
    
    
    [json setObject:params  forKey:@"parameters"];
    
    if (DEBUG_REQUEST) {
        return [json JSONRepresentation];
    } else {
        return [CryptoCR2 encrypt:[json JSONRepresentation]];
    }
}



@end
